{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import PromptTemplate\n",
    "\n",
    "# 定义模板\n",
    "template = \"\"\"作为一个广告专家，请为以下产品提供一个广告文案: {product}\"\"\"\n",
    "\n",
    "# 创建提示模板\n",
    "prompt = PromptTemplate(\n",
    "    input_variables=[\"product\"],\n",
    "    template=template\n",
    ")\n",
    "\n",
    "# 格式化提示\n",
    "formatted_prompt = prompt.format(product=\"华为Mate60 Pro手机\")\n",
    "\n",
    "# 打印格式化后的提示\n",
    "print(formatted_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import FewShotPromptTemplate, PromptTemplate\n",
    "from langchain.schema import HumanMessage\n",
    "from langchain_community.chat_models import ChatTongyi\n",
    "import os\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "# 加载环境变量\n",
    "load_dotenv()\n",
    "\n",
    "# 初始化聊天模型\n",
    "chat = ChatTongyi(\n",
    "    model='qwen-plus',\n",
    "    top_p=0.9,\n",
    "    temperature=0.9,\n",
    "    api_key=os.getenv(\"DASHSCOPE_API_KEY\")\n",
    ")\n",
    "\n",
    "# 创建示例\n",
    "examples = [\n",
    "    {\"input\": \"您喜欢的手机是什么？\", \"output\": \"我喜欢的手机是iPhone。\"},\n",
    "    {\"input\": \"您的喜欢手机的价格段位在多少？\", \"output\": \"我的预算在3000到5000元之间。\"},\n",
    "    {\"input\": \"您对手机改进任何建议吗？\", \"output\": \"我希望电池续航能够更长一些。\"},\n",
    "]\n",
    "\n",
    "# 定义格式化模板\n",
    "example_formatter_template = \"\"\"问题: {input} 答案: {output}\\n\"\"\"\n",
    "example_prompt = PromptTemplate(\n",
    "    input_variables=[\"input\", \"output\"],\n",
    "    template=example_formatter_template,\n",
    ")\n",
    "\n",
    "# 定义后缀\n",
    "suffix = \"问题: {input_var}\\n答案:\"\n",
    "\n",
    "# 创建 FewShotPromptTemplate 实例\n",
    "few_shot_prompt = FewShotPromptTemplate(\n",
    "    examples=examples,\n",
    "    example_prompt=example_prompt,\n",
    "    prefix=\"请回答以下问题：\",\n",
    "    suffix=suffix,\n",
    "    input_variables=[\"input_var\"],\n",
    "    example_separator=\"\\n\\n\",\n",
    ")\n",
    "\n",
    "# 定义待询问问题\n",
    "input_question = \"您最喜欢的手机颜色是什么？\"\n",
    "formatted_prompt = few_shot_prompt.format(input_var=input_question)\n",
    "\n",
    "# 将格式化后的提示包装为 HumanMessage，并传递给 chat()\n",
    "response = chat([HumanMessage(content=formatted_prompt)])\n",
    "\n",
    "# 打印模型的回复\n",
    "print(response.content)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "chatchat",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
